"""Database configuration module."""
import os
from sqlalchemy.ext.asyncio import create_async_engine, async_sessionmaker
from sqlalchemy.orm import declared_attr, DeclarativeBase

# The DATABASE_URL from docker-compose.yml will be sqlite:////srv/app/data/app.db
# We need to adapt it for async.
raw_db_url = os.getenv("DATABASE_URL", "sqlite:///./app_data.db")
if raw_db_url.startswith("sqlite:///"):
    async_db_url = raw_db_url.replace("sqlite:///", "sqlite+aiosqlite:///")
else:
    async_db_url = raw_db_url # Assume other dialects are already async compatible

engine = create_async_engine(async_db_url)

AsyncSessionLocal = async_sessionmaker(bind=engine, autoflush=False, autocommit=False)

class Base(DeclarativeBase):
    """Custom Declarative Base to allow __tablename__ defaults."""
    @declared_attr.directive
    def __tablename__(cls) -> str:
        return cls.__name__.lower()


async def get_async_session():
    """Dependency to get an async database session."""
    async with AsyncSessionLocal() as session:
        yield session
